<?php
/**
 * 用户模块
 * 
 * @author ShuangYa
 * @package TBSign
 * @category Model
 * @link http://www.sylingd.com/
 */

namespace tbsign\model;
use \sy\lib\YCookie;
use \sy\lib\db\YMysql;
use \sy\lib\YFetchURL;

class Member {
	static $_instance = NULL;
	static public function i() {
		if (self::$_instance === NULL) {
			self::$_instance = new self;
		}
		return self::$_instance;
	}
	public function get($uid) {
		return YMysql::i()->getOne('SELECT * FROM `#@__member` WHERE uid = ?', [$uid]);
	}
	public function getList() {
		return YMysql::i()->query('SELECT * FROM `#@__member`');
	}
	public function getLogin() {
		$token = YCookie::sGet('access_token', 2);
		//获取用户信息
		$userinfo = json_decode(YFetchURL::i([
			'url' => 'https://openapi.baidu.com/rest/2.0/passport/users/getLoggedInUser?' . http_build_query([
				'access_token' => $token,
				'format' => 'json'
			]),
			'header' => 0
		])->exec(), 1);
		if (empty($userinfo['uname'])) {
			return FALSE;
		}
		return $userinfo;
	}
	public function setUserValue($uid, $content) {
		$num = YMysql::i()->getOne('SELECT count(*) as num FROM `#@__member` WHERE uid = ?', [$uid]);
		if ($num['num'] == 0) {
			YMysql::i()->query("INSERT INTO `#@__member` (`uid`) VALUES ('$uid')");
		}
		$sql = 'UPDATE `#@__member` SET ';
		foreach ($content as $k => $v) {
			$sql .= $k . ' = ' . "'" . addslashes($v) . "', ";
		}
		$sql = rtrim($sql, ', ');
		$sql .= ' WHERE uid = ?';
		YMysql::i()->query($sql, [$uid]);
	}
}